<?php

namespace Rjyst\RjSongApi\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class UninstallCommand extends Command
{
    protected $signature = 'rj-song-api:uninstall {--force : Force uninstall without confirmation}';
    protected $description = 'Uninstall RjYst Song API package';

    public function handle()
    {
        $this->info('🗑️  开始卸载 RjYst Song API 扩展包...');

        if (!$this->option('force')) {
            if (!$this->confirm('确定要卸载 RjYst Song API 扩展包吗？这将删除相关文件和路由！')) {
                $this->info('卸载已取消');
                return;
            }
        }

        // 1. 删除控制器文件
        $this->deleteController();

        // 2. 移除路由
        $this->removeRoutes();

        $this->info('🎉 RjYst Song API 扩展包卸载完成！');
    }

    protected function deleteController()
    {
        $this->info('删除API控制器...');

        $controllerPath = app_path('Http/Controllers/Api/Song/SongController.php');

        if (File::exists($controllerPath)) {
            File::delete($controllerPath);
            $this->info('✅ 删除控制器: SongController.php');
        } else {
            $this->line('⚠️  控制器不存在: SongController.php');
        }

        // 检查并删除空目录
        $songDir = app_path('Http/Controllers/Api/Song');
        if (File::isDirectory($songDir) && count(File::allFiles($songDir)) === 0) {
            File::deleteDirectory($songDir);
            $this->info('✅ 删除空目录: Http/Controllers/Api/Song');
        }
    }

    protected function removeRoutes()
    {
        $this->info('移除API路由...');

        $routeFile = base_path('routes/api.php');

        if (!File::exists($routeFile)) {
            $this->warn('⚠️  routes/api.php 文件不存在');
            return;
        }

        $content = File::get($routeFile);

        // 移除 SongController 的 use 语句
        $content = str_replace("use App\Http\Controllers\Api\Song\SongController;\n", '', $content);
        $content = str_replace("\nuse App\Http\Controllers\Api\Song\SongController;", '', $content);

        // 移除 song 相关路由（包括注释）
        $patterns = [
            "/\s*\/\/歌曲歌谣\s*\n\s*Route::get\('song',\s*\[SongController::class,\s*'index'\]\)\s*->name\('song\.index'\);\s*/",
            "/\s*Route::get\('song\/\{songId\}',\s*\[SongController::class,\s*'caption'\]\)\s*->name\('song\.caption'\);\s*/",
        ];

        foreach ($patterns as $pattern) {
            $content = preg_replace($pattern, '', $content);
        }

        // 清理多余的空行
        $content = preg_replace("/\n{3,}/", "\n\n", $content);

        File::put($routeFile, $content);
        $this->info('✅ 路由移除完成');
    }
}
